#-------------------------------------------------------------------------------
# Name:        Database
# Purpose:
#
# Author:      Mr.Junz-N
#
# Created:     29/11/2012
# Copyright:   (c) Mr.Junz-N 2012
# Licence:     <1.0>
#-------------------------------------------------------------------------------

import sys
from Bootstrap import conf
from pymongo import Connection
from pymongo.errors import ConnectionFailure
HOST    = conf.HOST
PORT    = conf.PORT
class Database:
    def __init__(self):
        pass
    def Connect(self):
        """ Connect to MongoDb"""
        try:
            self.conn = Connection(HOST,PORT)
            print "Connection! Success"
        except ConnectionFailure,e:
            #sys.stderr.write("Error: %s"%e);
            print "\n\r"
            print "Connection failed"
            sys.exit(1)
        self.dbHandle = self.conn["BSIProject"]
        assert self.dbHandle.connection == self.conn
        print "Success"
        return True

#Close Connection
    def Close(self):
        self.conn.close()
    def InsertDocument(self, dictDoc):
        try:
            self.dbHandle.user.insert(dictDoc, safe = True, w=1) # w la so ban sao
        except OperationFailure:
            print "Write document fail"
            return False
        return True


    # //////////////////////////////////////////////////////////////////////////
    # @decription: Lay toan bo document cua Collection
    # @ param:
    #         dictCondition: 1 tu dien chua dieu kien truy van
    #
    # //////////////////////////////////////////////////////////////////////////
    def getAllDocument(self, dictCondition = {}):
        result = self.dbHandle.user.find(dictCondition, safe = True)
        return result


    # //////////////////////////////////////////////////////////////////////////
    # @ decription: Lay mot document
    # @ param:
    #         dictCondition: 1 tu dien chua dieu kien truy van
    #         param: Tham so trong truy van
    #
    # //////////////////////////////////////////////////////////////////////////

    def getOneDocumente(self, dictCondition = {}, param = {}):
        if param != None:
            result = self.dbHandle.user.find_one(dictCondition, safe = True)
            return result
        else:
            result = self.dbHandle.user.find_one(dictCondition, param , safe = True)
            return result
        pass


    # //////////////////////////////////////////////////////////////////////////
    # @ decription: Dem so truy van
    # @ param:
    #         dictCondition: 1 tu dien chua dieu kien truy van
    #         param: Tham so trong truy van
    #
    # //////////////////////////////////////////////////////////////////////////
    def getCountRecord(self):
        return self.dbHandle.user.find(safe = True).count()
        pass
#Writing Insert data to MongoDB
def main():
    # A user document demonstrating one-to-many relationships using embedding
    user_doc = {
    "username":"foouser",
    "emails":[
        { "email":"foouser1@example.com",  "primary":True },
        { "email":"foouser2@example2.com",  "primary":False},
        { "email":"foouser3@example3.com",  "primary":False}
        ]
    }
    db = Database()
    db.Connect()
    #db.InsertDocument({"name": "AnhNTD", "age":23})
    #for user in db.getAllDocument():
    #   print user["name"],"-",user["age"]
    #db.InsertDocument(user_doc)
    user_got = db.getOneDocumente({"emails.email":"foouser1@example.com"})
    #assert user_doc == user_got
    #print 1
    print user_got.get("username")

    #db.dbHandle.user.update({"name":"Mr. Junz"},{"$set":{"name": "ANH CHIEN"}}, multi = True, safe = True)
    #db.dbHandle.user.remove({"name":"ANH CHIEN"}, safe = True)
    print "Amount record have in collection: ", db.getCountRecord()

    pass
if __name__ == '__main__':
    main()
